package com.itheima.dao.impl;

import com.itheima.dao.StudentDao;
import com.itheima.daomain.Student;
import com.itheima.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> findAll()  {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        ArrayList<Student> students=new ArrayList<>();
        try {
            connection = JdbcUtils.getConnection();
            preparedStatement = connection.prepareStatement("select id,name,age from student");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                Student student = new Student(id,name,age);
                students.add(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JdbcUtils.close(connection,preparedStatement,resultSet);
        return students;
    }

   public int update (Student student) throws SQLException {
       Connection connection = null;
       PreparedStatement preparedStatement = null;
       ResultSet resultSet = null;
       int i=0;
       try {
           connection = JdbcUtils.getConnection();
           connection.setAutoCommit(false);
           Scanner sc=new Scanner(System.in);
           preparedStatement = connection.prepareStatement("update student set name=? age=? whrer id=?");
           preparedStatement.setObject(3,student.getId());
           preparedStatement.setObject(1,student.getName());
           preparedStatement.setObject(2,student.getAge());
           i = preparedStatement.executeUpdate();
       } catch (Exception e) {
           connection.rollback();
           e.printStackTrace();
       }finally {
           connection.commit();
           JdbcUtils.close(connection,preparedStatement,resultSet);
           return i;
       }

   }
    public int delete (Integer id)  {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            Scanner sc=new Scanner(System.in);
            preparedStatement = connection.prepareStatement("delete from student whrer  =?");
            System.out.println("请输入你要删除的id");
            preparedStatement.setObject(1,sc.nextLine());

        } catch (Exception e) {
            e.printStackTrace();
        }
        JdbcUtils.close(connection,preparedStatement,resultSet);
        return 1;
    }
}
